package v1

import (
	"gin-blog/app/models"
	"gin-blog/utils/re"
	"net/http"

	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"

	repo "gin-blog/app/repositories"
	"gin-blog/utils/errcode"
	"gin-blog/utils/helper"
	"gin-blog/utils/setting"
)

//获取多个文章标签
func GetTags(c *gin.Context) {
	var resp = re.Gin{C:c}
	maps := make(map[string]interface{})
	data := make(map[string]interface{})

	maps["state"] = 1

	if arg := c.Query("state"); arg != "" {
		state := com.StrTo(arg).MustInt()
		maps["state"] = state
	}

	code := errcode.SUCCESS

	data["list"] = repo.GetTags(helper.GetPage(c), setting.AppSetting.PageSize, maps)
	data["total"] = repo.GetTagsTotal(maps)

	resp.Response(http.StatusOK, code, "", data)
}

//新增文章标签
func AddTag(c *gin.Context) {
	var resp = re.Gin{C:c}
	var data = make(map[string]string)
	name := c.PostForm("name")
	author := c.DefaultPostForm("author", "admin")

	valid := validation.Validation{}
	valid.Required(name, "name").Message("不能为空")
	valid.MaxSize(name, 100, "name").Message("最长为100字符")

	code := errcode.INVALID_PARAMS

	if valid.HasErrors() {
		var msg string
		msg = re.RequestErrors(valid.Errors)
		resp.Response(http.StatusOK, code, msg, data)
		return
	}
	if repo.ExistTagByName(name) {
		resp.Response(http.StatusOK, code, "tag已存在", data)
		return
	}

	code = errcode.SUCCESS
	repo.AddTag(name, author)
	resp.Response(http.StatusOK, code, "", data)
}

//修改文章标签
func EditTag(c *gin.Context) {
	var resp = re.Gin{C:c}
	var data = make(map[string]string)
	name := c.PostForm("name")
	newname := c.PostForm("newname")
	author := c.PostForm("author")

	valid := validation.Validation{}
	valid.Required(name, "name").Message("不能为空")
	valid.Required(newname, "newname").Message("不能为空")
	valid.Required(author, "author").Message("不能为空")

	code := errcode.INVALID_PARAMS
	var msg string

	if valid.HasErrors() {
		msg = re.RequestErrors(valid.Errors)
		resp.Response(http.StatusOK, code, msg, data)
		return
	}

	code = errcode.SUCCESS
	tmpTagInfo := repo.GetTag(name)

	if len(tmpTagInfo) == 0 {
		resp.Response(http.StatusOK, code, "无此tag", data)
		return
	}
	tagInfo := models.Tag{}
	tagInfo = tmpTagInfo[0]

	if tagInfo.Author != author {
		msg = "非作者本人不可修改"
		resp.Response(http.StatusOK, code, msg, data)
		return
	}

	var updateData = make(map[string]interface{})
	updateData["name"] = newname
	repo.EditTag(tagInfo.ID, updateData)
	resp.Response(http.StatusOK, code, "", data)
}

//删除文章标签
func DeleteTag(c *gin.Context) {
	var resp = re.Gin{C:c}
	var data = make(map[string]string)
	id := com.StrTo(c.Param("id")).MustInt()
	valid := validation.Validation{}
	code := errcode.INVALID_PARAMS

	valid.Required(id, "id").Message("不能为空")

	if valid.HasErrors() {
		var msg string
		msg = re.RequestErrors(valid.Errors)
		resp.Response(http.StatusOK, code, msg, data)
		return
	}

	repo.DeleteTag(id)
	code = errcode.SUCCESS
	resp.Response(http.StatusOK, code, "", data)
}
